package com.tn.tcp;

import cn.hutool.core.util.ArrayUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;

@Slf4j
public class NettyExt {
    public static void sendMessage(ChannelHandlerContext ctx, String body, boolean... showlog) {
        if(showlog.length == 1 && showlog[0]) {
            log.info("{} --> {}: {}", getServerPort(ctx), getClientIp(ctx), body);
        }
        ctx.writeAndFlush(strToBuffer(body));
    }
    public static void sendMessage(ChannelHandlerContext ctx, ByteBuf buf, boolean... showlog) {
        if(showlog.length == 1 && showlog[0]) {
            log.info("{} --> {}: {}", getServerPort(ctx), getClientIp(ctx), buf.toString());
        }
        ctx.writeAndFlush(buf);
    }

    public static ByteBuf strToBuffer(String msg) {
        try {
            return Unpooled.copiedBuffer(msg.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            log.error("strToBuffer: {}", e);
            return null;
        }
    }

    public static String bufToStr(ByteBuf buf) {
        return buf.toString(CharsetUtil.UTF_8);
    }

    public static String getClientIp(ChannelHandlerContext ctx) {
        return ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
    }
    public static int getServerPort(ChannelHandlerContext ctx) {
        return ((InetSocketAddress)ctx.channel().localAddress()).getPort();
    }

    public static boolean portNotMatched(ChannelHandlerContext ctx, int port, int... ports) {
        int serverPort = ((InetSocketAddress)ctx.channel().localAddress()).getPort();
        return port != serverPort && !ArrayUtil.contains(ports, serverPort);
    }
}
